package com.sduept.nwld.secondaryequipment.evaluation.rest;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sduept.bigdata.fault.protection.model.ProtectDeviceAlarmModel;
import com.sduept.bigdata.fault.protection.model.ProtectInterruptAlarm;
import com.sduept.bigdata.fault.protection.model.ProtectionActionInfoDTO;
import com.sduept.bigdata.fault.protection.service.ProtectDeviceAlarmQueryManager;
import com.sduept.bigdata.fault.protection.service.ProtectionActionQueryManager;
import com.sduept.bigdata.risk.assessment.model.SecondaryEquipmentCheckInfo;
import com.sduept.bigdata.risk.assessment.model.SecondaryEquipmentCounterMeasuresSubInfo;
import com.sduept.bigdata.risk.assessment.model.SecondaryEquipmentDefectInfo;
import com.sduept.bigdata.risk.service.EquipmentAssessmentManager;
import com.sduept.bigdata.risk.service.EquipmentAssessmentManager.EquipmentAssessment;
import com.sduept.bigdata.risk.service.EquipmentAssessmentManager.StationAssessmentModel;
import com.sduept.bigdata.risk.service.EquipmentCheckQueryManager;
import com.sduept.bigdata.risk.service.EquipmentCounterMeasuresQueryManager;
import com.sduept.bigdata.risk.service.EquipmentDefectQueryManager;
import com.sduept.bigdata.risk.service.RiskAssessmentManager;
import com.sduept.bigdata.weather.manager.TyphoonManager;
import com.sduept.bigdata.weather.manager.WeatherWarningCache;
import com.sduept.cim.ledger.manager.EquipmentLedgerManager;
import com.sduept.cim.ledger.model.SecondaryEquipmentLedger;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.utils.DateUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@RestController
@RequestMapping("/SecRiskEvaluateService")
public class SecRiskEvaluateService {	
	@Autowired
	private ProtectionActionQueryManager paqm;
	@Autowired
	private EquipmentCheckQueryManager ecqm;	
	@Autowired
	private ProtectDeviceAlarmQueryManager pdaqm;	
	@Autowired
	private EquipmentDefectQueryManager edqm;
	@Autowired
	private EquipmentLedgerManager elqm;
	@Autowired
	private EquipmentCounterMeasuresQueryManager ecmqm;
	@Autowired
	private EquipmentAssessmentManager ea;
	@Autowired
	private CimManager cim;
	@Autowired
	private TyphoonManager tm;
	@Autowired
	private WeatherWarningCache wwm;
	@Autowired
	private RiskAssessmentManager ram;

	/**
	 * 根据站id获取该站的二次设备各项目风险评估
	 * 
	 * @param
	 * @return {name:[[],[]],name:[]}
	 */

	@GetMapping("/getSecRiskProject/{stationId}")
	public String getSecRiskProject(@PathVariable("stationId") String sid) {
		// String[] type ={ "反措未执行", "家族性缺陷", "超期服役", "超期未检", "通信中断",
		// "保护装置异常" };
		EquipmentAssessment equip = ea.getSecondaryEquipmentAssessment(sid);
		JSONObject jso = new JSONObject();
		jso.put("反措未执行",
				equip.getSecondaryEquipmentCounterMeasuresInfoList() == null ? ""
						: equip.getSecondaryEquipmentCounterMeasuresInfoList());
		jso.put("未处理缺陷",
				equip.getSecondaryEquipmentDefectInfoList() == null ? ""
						: equip.getSecondaryEquipmentDefectInfoList());
		jso.put("超期服役", equip.getSecondaryEquipmentLedgerList() == null ? ""
				: equip.getSecondaryEquipmentLedgerList());
		jso.put("超期未检", equip.getSecondaryEquipmentCheckInfoList() == null ? ""
				: equip.getSecondaryEquipmentCheckInfoList());
		jso.put("通信中断", equip.getProtectInterruptAlarmList() == null ? ""
				: equip.getProtectInterruptAlarmList());
		jso.put("保护装置异常", equip.getProtectDeviceAlarmList() == null ? ""
				: equip.getProtectDeviceAlarmList());
		jso.put("保护响应异常",
				equip.getSecondaryEquipmentExceptionList() == null ? "" : equip
						.getSecondaryEquipmentExceptionList());
		return jso.toString();
	}

	/**
	 * 根据站id获取该站的二次设备各项目风险评估
	 * 
	 * @param
	 * @return {name:[[],[]],name:[]}
	 */

	@GetMapping("/getSecRiskProject4PieChart/{stationId}")
	public String getSecRiskProject4PieChart(@PathVariable("stationId") String sid) {
		return getPieChartOptionData(sid);
	}

	/**
	 * 全网二次设备风险评估站点风险等级(暂时忽略通信中断)
	 * 
	 * @param
	 * @return
	 */

	@GetMapping("/getSecondRiskLevel")
	public String getSecondRiskLevel() {
		Collection<StationAssessmentModel> result = ea
				.getStationSecondaryEquipmentAssessmentResult();
		JSONObject jso = new JSONObject();
		JSONArray rtn = new JSONArray();
		for (StationAssessmentModel s : result) {
			JSONObject jo = new JSONObject();
			// int level = r.nextInt(100);
			JSONObject jo1 = new JSONObject();
			jo1.put("latitude", s.getLatitude());
			jo1.put("longitude", s.getLongitude());
			jo1.put("name", s.getStationName());
			jo1.put("id", s.getStationId());
			jo.put("station", jo1);
			jo.put("level", s.getLevel());
			jo.put("style", s.getStyle());
			jo.put("info", getMapPieChartOptionData(s.getStationId()));
			rtn.add(jo);
		}
		jso.put("stations", rtn);
		jso.put("count", getTotalRiskTypeCount());
		jso.put("levelCount",
				EquipmentAssessmentManager.SECOND_RISK_GROUP.length);
		jso.put("levelColor",
				EquipmentAssessmentManager.SECOND_RISK_GROUP_COLOR);
		return jso.toString();
	}
	/**
	 * 全网二次设备异常统计，用在风险告警处,统计各种异常类型的个数(暂时忽略通信中断)
	 * 
	 * @param
	 * @return
	 */

	@GetMapping("/getSecondExpCount")
	public String getSecondExpCount() {
		return getTotalRiskTypeCount().toString();
	}

	/**
	 * 按评估类型找站点（风险告警找那个点击异常统计表头）
	 * 
	 * @param
	 * @return
	 */

	@GetMapping("/getSecondRiskStationByType/{type}")
	public String getSecondRiskStationByType(@PathVariable("type") String type) {
		List<StationAssessmentModel> result = ea
				.getSecondaryRiskInfoByType(type);
		JSONArray rtn = new JSONArray();
		for (StationAssessmentModel s : result) {
			JSONObject jo = new JSONObject();
			JSONObject jo1 = new JSONObject();
			jo1.put("latitude", s.getLatitude());
			jo1.put("longitude", s.getLongitude());
			jo1.put("name", s.getStationName());
			jo1.put("id", s.getStationId());
			jo.put("station", jo1);
			jo.put("style", s.getStyle());
			rtn.add(jo);
		}
		return rtn.toString();
	}

	/**
	 * 按评估类型和站的id找所有信息
	 * 
	 * @param
	 * @return
	 */

	@GetMapping("/getSecondInfoByType/{type}/{stationId}")
	public String getInfoByType(@PathVariable("type") String type,
			@PathVariable("stationId") String stationId) {
		return this.getSecondaryInfoByType(type, stationId).toString();
	}
	
	
	/**
	 * 按类型和站点的id统计二次设备风险评估详细信息
	 * */
	private JSONObject getSecondaryInfoByType(String type,String stationId){
		Date[] ds = getStartEndDate();
		Date start = ds[0];
		Date end = ds[1];
		JSONObject jso=new JSONObject();
		List<ProtectionEquipment> ps = cim.getProtectionEquipmentsByStationId(stationId);
		int total = ps.size();
		switch(type){
		case "secondTypeservice":
			List<SecondaryEquipmentLedger> overdueRunList = elqm.getOverdueSecondaryEquipmentLedgerByStationId(stationId);
			Map<String,List<SecondaryEquipmentLedger>> overdueRunLists=new HashMap<String,List<SecondaryEquipmentLedger>>();
			if(overdueRunList!=null && !overdueRunList.isEmpty()){
				Set<String> odrnames=new HashSet<String>();
				for(SecondaryEquipmentLedger _overdueRunList:overdueRunList){
					if(_overdueRunList.getName()!=null){
						odrnames.add(_overdueRunList.getName());
					}
				}				
				if(!odrnames.isEmpty()){
					for(String odrname:odrnames){
						List<SecondaryEquipmentLedger> _overdueRunLists=new ArrayList<SecondaryEquipmentLedger>();
						for(SecondaryEquipmentLedger __overdueRunLists:overdueRunList){
							if(__overdueRunLists.getName()!=null && __overdueRunLists.getName().equals(odrname)){
								_overdueRunLists.add(__overdueRunLists);
							}
						}						
						overdueRunLists.put(odrname,_overdueRunLists);						
					}
				}
			}
		    jso.put("info", overdueRunLists);  
		    break;
		case "secondTypecheck":
			List<SecondaryEquipmentCheckInfo> overdueCheckList = ecqm.getSecondaryEquipmentOverdueCheckInfoByStationId(stationId,start,end);
			Map<String,List<SecondaryEquipmentCheckInfo>> overdueCheckLists=new HashMap<String,List<SecondaryEquipmentCheckInfo>>();
			if(overdueCheckList!=null && !overdueCheckList.isEmpty()){
				Set<String> oc_names=new HashSet<String>();
				for(SecondaryEquipmentCheckInfo _overdueCheckList:overdueCheckList){
					if(_overdueCheckList.getDeviceName()!=null){
						oc_names.add(_overdueCheckList.getDeviceName());
					}
				}				
				if(!oc_names.isEmpty()){
					for(String oc_name:oc_names){
						List<SecondaryEquipmentCheckInfo> _overdueCheckLists=new ArrayList<SecondaryEquipmentCheckInfo>();
						for(SecondaryEquipmentCheckInfo __overdueCheckList:overdueCheckList){
							if(__overdueCheckList.getDeviceName()!=null && __overdueCheckList.getDeviceName().equals(oc_name)){
								_overdueCheckLists.add(__overdueCheckList);
							}
						}						
						overdueCheckLists.put(oc_name,_overdueCheckLists);						
					}
				}
			}
		    jso.put("info", overdueCheckLists);  
		    break;
		case "secondTypecounter":
			List<SecondaryEquipmentCounterMeasuresSubInfo>  overdueCounterMeasuresList = ecmqm.getSecondaryEquipmentOverdueCounterMeasuresInfoByStationId(stationId,start,end);
			Map<String,List<SecondaryEquipmentCounterMeasuresSubInfo>> overdueCounterMeasuresLists=new HashMap<String,List<SecondaryEquipmentCounterMeasuresSubInfo>>();
			if(overdueCounterMeasuresList!=null && !overdueCounterMeasuresList.isEmpty()){
				Set<String> ocm_names=new HashSet<String>();
				for(SecondaryEquipmentCounterMeasuresSubInfo _overdueCounterMeasuresList:overdueCounterMeasuresList){
					if(_overdueCounterMeasuresList.getDeviceName()!=null){
						ocm_names.add(_overdueCounterMeasuresList.getDeviceName());
					}
				}				
				if(!ocm_names.isEmpty()){
					for(String ocm_name:ocm_names){
						List<SecondaryEquipmentCounterMeasuresSubInfo> _overdueCounterMeasuresLists=new ArrayList<SecondaryEquipmentCounterMeasuresSubInfo>();
						for(SecondaryEquipmentCounterMeasuresSubInfo __overdueCounterMeasuresList:overdueCounterMeasuresList){
							if(__overdueCounterMeasuresList.getDeviceName()!=null && __overdueCounterMeasuresList.getDeviceName().equals(ocm_name)){
								_overdueCounterMeasuresLists.add(__overdueCounterMeasuresList);
							}
						}						
						overdueCounterMeasuresLists.put(ocm_name,_overdueCounterMeasuresLists);						
					}
				}
			}
		    jso.put("info", overdueCounterMeasuresLists);  
		    break;
		case "secondTypedefect":
			List<SecondaryEquipmentDefectInfo> defectList = edqm.getUnsolveSecondaryEquipmentDefectInfoByStationId(stationId,start,end);
			Map<String,List<SecondaryEquipmentDefectInfo>> defectLists=new HashMap<String,List<SecondaryEquipmentDefectInfo>>();
			if(defectList!=null && !defectList.isEmpty()){
				Set<String> equ_names=new HashSet<String>();
				for(SecondaryEquipmentDefectInfo _defectList:defectList){
					if(_defectList.getDeviceName()!=null){
						equ_names.add(_defectList.getDeviceName());
					}
				}				
				if(!equ_names.isEmpty()){
					for(String equ_name:equ_names){
						List<SecondaryEquipmentDefectInfo> _defectLists=new ArrayList<SecondaryEquipmentDefectInfo>();
						for(SecondaryEquipmentDefectInfo __defectList:defectList){
							if(__defectList.getDeviceName()!=null&&__defectList.getDeviceName().equals(equ_name)){
								_defectLists.add(__defectList);
							}
						}						
						defectLists.put(equ_name,_defectLists);						
					}
				}
			}
		    jso.put("info", defectLists); 
		    break;
		case "secondTypechannel":
			List<ProtectInterruptAlarm> ctList = pdaqm.getProtectInterruptAlarmByStationAndDate(stationId,start, end);
			Map<String,List<ProtectInterruptAlarm>> ctLists=new HashMap<String,List<ProtectInterruptAlarm>>();
			if(ctList!=null && !ctList.isEmpty()){
				Set<String> bh_names=new HashSet<String>();
				for(ProtectInterruptAlarm _ctList:ctList){
					if(_ctList.getLineName()!=null&&_ctList.getProtectType()!=null){
						bh_names.add(_ctList.getLineName()+_ctList.getProtectType());
					}
				}				
				if(!bh_names.isEmpty()){
					for(String bh_name:bh_names){
						List<ProtectInterruptAlarm> _ctLists=new ArrayList<ProtectInterruptAlarm>();
						for(ProtectInterruptAlarm __ctList:ctList){
							if(__ctList.getProtectName()!=null&&(__ctList.getLineName()+__ctList.getProtectType()).equals(bh_name)){
								_ctLists.add(__ctList);
							}
						}						
						ctLists.put(bh_name,_ctLists);						
					}
				}
			}
		    jso.put("info", ctLists); 
		    break;
		case "secondTypedevice":	
			//装置异常
			List<ProtectDeviceAlarmModel> deviceAlarmList= pdaqm.getFrequentProtectDeviceAlarmByStationAndDate(stationId,start,end);
			Map<String,List<ProtectDeviceAlarmModel>> daLists=new HashMap<String,List<ProtectDeviceAlarmModel>>();
			if(deviceAlarmList!=null && !deviceAlarmList.isEmpty()){
				Set<String> protectNames=new HashSet<String>();
				for(ProtectDeviceAlarmModel _deviceAlarmList:deviceAlarmList){
					protectNames.add(_deviceAlarmList.getProtectName());
				}				
				if(!protectNames.isEmpty()){
					for(String protectName:protectNames){
						List<ProtectDeviceAlarmModel> _deviceAlarmLists=new ArrayList<ProtectDeviceAlarmModel>();
						for(ProtectDeviceAlarmModel __deviceAlarmList:deviceAlarmList){
							if(__deviceAlarmList.getProtectName().equals(protectName)){
								_deviceAlarmLists.add(__deviceAlarmList);
							}
						}						
						daLists.put(protectName,_deviceAlarmLists);						
					}
				}
			}
		    jso.put("info", daLists); 
		    break;
		case "secondTyperesponse":
			List<ProtectionActionInfoDTO> protectExceptionList = paqm.getProtectExceptionCountByStationId(stationId,start,end);
			Map<String,List<ProtectionActionInfoDTO>> peLists=new HashMap<String,List<ProtectionActionInfoDTO>>();
			if(protectExceptionList!=null && !protectExceptionList.isEmpty()){
				Set<String> protectionNames=new HashSet<String>();
				for(ProtectionActionInfoDTO _protectExceptionList:protectExceptionList){
					protectionNames.add(_protectExceptionList.getLineName()+_protectExceptionList.getType());
				}				
				if(!protectionNames.isEmpty()){
					for(String protectionName:protectionNames){
						List<ProtectionActionInfoDTO> _protectExceptionLists=new ArrayList<ProtectionActionInfoDTO>();
						for(ProtectionActionInfoDTO __protectExceptionList:protectExceptionList){
							if((__protectExceptionList.getLineName()+__protectExceptionList.getType()).equals(protectionName)){
								_protectExceptionLists.add(__protectExceptionList);
							}
						}						
						peLists.put(protectionName,_protectExceptionLists);						
					}
				}
			}
		    jso.put("info", peLists); 
		    break;
		default:
			break;
	   }
		jso.put("count", total);
		return jso;
	}
	
	private Date[] getStartEndDate(){
		Date[] ds = new Date[2];
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		String startDateStr = year+"-01-01 00:00:00";
		String endDateStr = DateUtil.getStringDate(new Date(), DateUtil.pattern_ymd)+" 23:59:59";
		
		Date start = DateUtil.getDateByString(startDateStr, DateUtil.pattern_ymdhms);
		Date end = DateUtil.getDateByString(endDateStr, DateUtil.pattern_ymdhms);
		ds[0]=start;
		ds[1]=end;
		return ds;
	}

	private String[] getSecondaryRiskTypeByLevel(String level) {
		if ("高风险".equals(level)) {
			return new String[] { "保护装置异常","保护响应异常"  };
		} else if ("中等风险".equals(level)) {
			return new String[] { "反措未执行", "未处理缺陷",};
		} else if ("低风险".equals(level)) {
			return new String[] { "超期服役", "超期未检"};
		} else {
			return new String[] {};
		}
	}

	/**
	 * 获取单个变电站的评估数据
	 * 
	 * @param sid
	 * @return
	 */
	private String getPieChartOptionData(String sid) {
		// 获取变电站二次设备数量
		List<ProtectionEquipment> ps = cim
				.getProtectionEquipmentsByStationId(sid);
		int total = ps.size();
		JSONObject countJso = new JSONObject();
		countJso.put("total", total);
		// 获取影响风险等级的各个具体的记录列表
		EquipmentAssessment equip = ea.getSecondaryEquipmentAssessment(sid);
		JSONObject typeCountjso = new JSONObject();

		// 反措未执行
		List<SecondaryEquipmentCounterMeasuresSubInfo> fcs = equip
				.getSecondaryEquipmentCounterMeasuresInfoList();
		Map<String, List<SecondaryEquipmentCounterMeasuresSubInfo>> fcInfos = this
				.generateSecondaryEquipmentCounterMeasuresSubInfo(fcs);
		typeCountjso.put("反措未执行", fcInfos);

		// 未处理缺陷
		List<SecondaryEquipmentDefectInfo> defects = equip
				.getSecondaryEquipmentDefectInfoList();
		Map<String, List<SecondaryEquipmentDefectInfo>> defectInfos = this
				.generateSecondaryEquipmentDefectInfo(defects);
		typeCountjso.put("未处理缺陷", defectInfos);

		// 超期服役
		List<SecondaryEquipmentLedger> ledger = equip
				.getSecondaryEquipmentLedgerList();
		Map<String, List<SecondaryEquipmentLedger>> ledgerInfos = this
				.generateSecondaryEquipmentLedger(ledger);
		typeCountjso.put("超期服役", ledgerInfos);

		// 超期未检
		List<SecondaryEquipmentCheckInfo> checks = equip
				.getSecondaryEquipmentCheckInfoList();
		Map<String, List<SecondaryEquipmentCheckInfo>> checkInfos = this
				.generateSecondaryEquipmentCheckInfo(checks);
		typeCountjso.put("超期未检", checkInfos);

		// 通信中断
		/*List<ProtectDeviceAlarmModel> channelAlarms = equip.getProtectInterruptAlarmList();
		Map<String, List<ProtectDeviceAlarmModel>> channelAlarmInfos = this
				.generateProtectChannelAlarm(channelAlarms);
		typeCountjso.put("通信中断", channelAlarmInfos);*/

		// 保护装置异常
		List<ProtectDeviceAlarmModel> devAlarms = equip.getProtectDeviceAlarmList();
		Map<String, List<ProtectDeviceAlarmModel>> devAlarmInfos = this
				.generateProtectDeviceAlarm(devAlarms);
		typeCountjso.put("保护装置异常", devAlarmInfos);

		// 保护响应异常
		List<ProtectionActionInfoDTO> protectExceptionList = equip
				.getSecondaryEquipmentExceptionList();
		Map<String, List<ProtectionActionInfoDTO>> peInfos = this
				.generateProtectionActionInfoDTO(protectExceptionList);
		typeCountjso.put("保护响应异常", peInfos);

		JSONObject jso = new JSONObject();
		// 主饼图数据[{name:xxx,value:1}]
		JSONArray pieMainValues = new JSONArray();
		// 外围饼图数据[{name:xxx,value:1}],顺序要和主饼图保持一致
		JSONArray pieSubValues = new JSONArray();
		String conclusion = "共有二次设备" + total + "个  ";
		// 右边说明{"高风险":{"CT饱和":0,"断路器动作异常":1},"低风险":{"超期未检":1}}
		JSONObject descJso = new JSONObject();
		for (String g : EquipmentAssessmentManager.SECOND_RISK_GROUP) {
			Map<String, Integer> descMap = new HashMap<>();
			JSONObject tmp = new JSONObject();
			String[] types = getSecondaryRiskTypeByLevel(g);
			int count = 0;
			if ("正常".equals(g)) {
				count = total - fcInfos.size() - defectInfos.size()
						- ledgerInfos.size() - checkInfos.size()
						- devAlarmInfos.size()
						- peInfos.size();
				JSONObject tmpsub = new JSONObject();
				tmpsub.put("name", g);
				tmpsub.put("value", count);
				tmpsub.put("itemStyle", getGroupColor(g));
				pieSubValues.add(tmpsub);
			} else {
				for (String ts : types) {
					Object tclist = typeCountjso.get(ts);
					if (tclist != null && tclist instanceof Map) {
						int cttmp = ((Map) typeCountjso.get(ts)).size();// 设备数目
						if (cttmp != 0) {
							count += cttmp;
							JSONObject tmpsub = new JSONObject();
							tmpsub.put("name", ts);
							tmpsub.put("value", cttmp);
							pieSubValues.add(tmpsub);
						}
						descMap.put(ts, cttmp);
					}
					descJso.put(g, descMap);
				}
			}
			if (count != 0) {
				tmp.put("name", g);
				tmp.put("value", count);
				if ("高风险".equals(g)) {
					tmp.put("selected", true);
				}
				tmp.put("itemStyle", getGroupColor(g));
				conclusion += g + count + "个  ";
				pieMainValues.add(tmp);
			}
		}
		jso.put("pieMain", pieMainValues);// 饼图
		jso.put("pieSub", pieSubValues);// 环图
		jso.put("subDatas", typeCountjso);// 两个小饼图
		jso.put("counts", countJso);// 设备总数
		jso.put("conclusion", conclusion);// 总结
		jso.put("desc", descJso);// 说明
		return jso.toString();
	}

	/**
	 * 构造保护响应异常Map集合
	 * 
	 * @param protectExceptionList
	 *            {name:valueList}
	 * @return
	 */
	private Map<String, List<ProtectionActionInfoDTO>> generateProtectionActionInfoDTO(
			List<ProtectionActionInfoDTO> protectExceptionList) {
		Map<String, List<ProtectionActionInfoDTO>> peLists = new HashMap<String, List<ProtectionActionInfoDTO>>();
		if (protectExceptionList != null && !protectExceptionList.isEmpty()) {
			Set<String> protectionNames = new HashSet<String>();
			for (ProtectionActionInfoDTO _protectExceptionList : protectExceptionList) {
				protectionNames.add(_protectExceptionList.getLineName().replace("500kv", "")
						+ _protectExceptionList.getType());
			}
			if (!protectionNames.isEmpty()) {
				for (String protectionName : protectionNames) {
					List<ProtectionActionInfoDTO> _protectExceptionLists = new ArrayList<ProtectionActionInfoDTO>();
					for (ProtectionActionInfoDTO __protectExceptionList : protectExceptionList) {
						if ((__protectExceptionList.getLineName().replace("500kv", "") + __protectExceptionList
								.getType()).equals(protectionName)) {
							_protectExceptionLists.add(__protectExceptionList);
						}
					}
					peLists.put(protectionName, _protectExceptionLists);
				}
			}
		}
		return peLists;
	}

	/**
	 * 构造保护装置异常Map集合
	 * 
	 * @param devAlarms
	 * @return
	 */
	private Map<String, List<ProtectDeviceAlarmModel>> generateProtectDeviceAlarm(
			List<ProtectDeviceAlarmModel> devAlarms) {
		Map<String, List<ProtectDeviceAlarmModel>> peLists = new HashMap<String, List<ProtectDeviceAlarmModel>>();
		if (devAlarms != null && !devAlarms.isEmpty()) {
			Set<String> protectionNames = new HashSet<String>();
			for (ProtectDeviceAlarmModel _protectExceptionList : devAlarms) {
				protectionNames.add(_protectExceptionList.getProtectName());
			}
			if (!protectionNames.isEmpty()) {
				for (String protectionName : protectionNames) {
					List<ProtectDeviceAlarmModel> _protectExceptionLists = new ArrayList<ProtectDeviceAlarmModel>();
					for (ProtectDeviceAlarmModel __protectExceptionList : devAlarms) {
						if ((__protectExceptionList.getProtectName()).equals(protectionName)) {
							_protectExceptionLists.add(__protectExceptionList);
						}
					}
					peLists.put(protectionName, _protectExceptionLists);
				}
			}
		}
		return peLists;
	}

	/**
	 * 构造通信中断Map集合
	 * 
	 * @param channelAlarms
	 * @return
	 */
	private Map<String, List<ProtectDeviceAlarmModel>> generateProtectChannelAlarm(
			List<ProtectDeviceAlarmModel> channelAlarms) {
		Map<String, List<ProtectDeviceAlarmModel>> peLists = new HashMap<String, List<ProtectDeviceAlarmModel>>();
		if (channelAlarms != null && !channelAlarms.isEmpty()) {
			Set<String> protectionNames = new HashSet<String>();
			for (ProtectDeviceAlarmModel _protectExceptionList : channelAlarms) {
				protectionNames.add(_protectExceptionList.getProtectName());
			}
			if (!protectionNames.isEmpty()) {
				for (String protectionName : protectionNames) {
					List<ProtectDeviceAlarmModel> _protectExceptionLists = new ArrayList<ProtectDeviceAlarmModel>();
					for (ProtectDeviceAlarmModel __protectExceptionList : channelAlarms) {
						if ((__protectExceptionList.getProtectName()).equals(
								protectionName)) {
							_protectExceptionLists.add(__protectExceptionList);
						}
					}
					peLists.put(protectionName, _protectExceptionLists);
				}
			}
		}
		return peLists;
	}

	/**
	 * 构造超期未检Map集合
	 * 
	 * @param checks
	 * @return
	 */
	private Map<String, List<SecondaryEquipmentCheckInfo>> generateSecondaryEquipmentCheckInfo(
			List<SecondaryEquipmentCheckInfo> checks) {
		Map<String, List<SecondaryEquipmentCheckInfo>> peLists = new HashMap<String, List<SecondaryEquipmentCheckInfo>>();
		if (checks != null && !checks.isEmpty()) {
			Set<String> protectionNames = new HashSet<String>();
			for (SecondaryEquipmentCheckInfo _protectExceptionList : checks) {
				protectionNames.add(_protectExceptionList.getDeviceName());
			}
			if (!protectionNames.isEmpty()) {
				for (String protectionName : protectionNames) {
					List<SecondaryEquipmentCheckInfo> _protectExceptionLists = new ArrayList<SecondaryEquipmentCheckInfo>();
					for (SecondaryEquipmentCheckInfo __protectExceptionList : checks) {
						if (__protectExceptionList.getDeviceName().equals(
								protectionName)) {
							_protectExceptionLists.add(__protectExceptionList);
						}
					}
					peLists.put(protectionName, _protectExceptionLists);
				}
			}
		}
		return peLists;
	}

	/**
	 * 构造反措未执行Map集合
	 * 
	 * @param ledger
	 * @return
	 */
	private Map<String, List<SecondaryEquipmentCounterMeasuresSubInfo>> generateSecondaryEquipmentCounterMeasuresSubInfo(
			List<SecondaryEquipmentCounterMeasuresSubInfo> ledger) {
		Map<String, List<SecondaryEquipmentCounterMeasuresSubInfo>> peLists = new HashMap<String, List<SecondaryEquipmentCounterMeasuresSubInfo>>();
		if (ledger != null && !ledger.isEmpty()) {
			Set<String> protectionNames = new HashSet<String>();
			for (SecondaryEquipmentCounterMeasuresSubInfo _protectExceptionList : ledger) {
				protectionNames.add(_protectExceptionList.getDeviceName());
			}
			if (!protectionNames.isEmpty()) {
				for (String protectionName : protectionNames) {
					List<SecondaryEquipmentCounterMeasuresSubInfo> _protectExceptionLists = new ArrayList<SecondaryEquipmentCounterMeasuresSubInfo>();
					for (SecondaryEquipmentCounterMeasuresSubInfo __protectExceptionList : ledger) {
						if (__protectExceptionList.getDeviceName().equals(
								protectionName)) {
							_protectExceptionLists.add(__protectExceptionList);
						}
					}
					peLists.put(protectionName, _protectExceptionLists);
				}
			}
		}
		return peLists;
	}

	/**
	 * 构造未处理缺陷Map集合
	 * 
	 * @param defects
	 * @return
	 */
	private Map<String, List<SecondaryEquipmentDefectInfo>> generateSecondaryEquipmentDefectInfo(
			List<SecondaryEquipmentDefectInfo> defects) {
		Map<String, List<SecondaryEquipmentDefectInfo>> peLists = new HashMap<String, List<SecondaryEquipmentDefectInfo>>();
		if (defects != null && !defects.isEmpty()) {
			Set<String> protectionNames = new HashSet<String>();
			for (SecondaryEquipmentDefectInfo _protectExceptionList : defects) {
				protectionNames.add(_protectExceptionList.getDeviceName());
			}
			if (!protectionNames.isEmpty()) {
				for (String protectionName : protectionNames) {
					List<SecondaryEquipmentDefectInfo> _protectExceptionLists = new ArrayList<SecondaryEquipmentDefectInfo>();
					for (SecondaryEquipmentDefectInfo __protectExceptionList : defects) {
						if (__protectExceptionList.getDeviceName().equals(
								protectionName)) {
							_protectExceptionLists.add(__protectExceptionList);
						}
					}
					peLists.put(protectionName, _protectExceptionLists);
				}
			}
		}
		return peLists;
	}

	/**
	 * 构建超期服役Map集合
	 * 
	 * @param fcs
	 * @return
	 */
	private Map<String, List<SecondaryEquipmentLedger>> generateSecondaryEquipmentLedger(
			List<SecondaryEquipmentLedger> fcs) {
		Map<String, List<SecondaryEquipmentLedger>> peLists = new HashMap<String, List<SecondaryEquipmentLedger>>();
		if (fcs != null && !fcs.isEmpty()) {
			Set<String> protectionNames = new HashSet<String>();
			for (SecondaryEquipmentLedger _protectExceptionList : fcs) {
				protectionNames.add(_protectExceptionList.getName());
			}
			if (!protectionNames.isEmpty()) {
				for (String protectionName : protectionNames) {
					List<SecondaryEquipmentLedger> _protectExceptionLists = new ArrayList<SecondaryEquipmentLedger>();
					for (SecondaryEquipmentLedger __protectExceptionList : fcs) {
						if (__protectExceptionList.getName().equals(
								protectionName)) {
							_protectExceptionLists.add(__protectExceptionList);
						}
					}
					peLists.put(protectionName, _protectExceptionLists);
				}
			}
		}
		return peLists;
	}

	private JSONObject getGroupColor(String g) {
		JSONObject normal = new JSONObject();
		JSONObject color = new JSONObject();
		for (int i = 0; i < EquipmentAssessmentManager.SECOND_RISK_GROUP.length; i++) {
			if (EquipmentAssessmentManager.SECOND_RISK_GROUP[i].equals(g)) {
				color.put("color",
						EquipmentAssessmentManager.SECOND_RISK_GROUP_COLOR[i]);
				break;
			}
		}
		normal.put("normal", color);
		return normal;
	}

	/**
	 * 获取风险评估各个因素的统计总数
	 * 
	 * @return
	 */
	private JSONObject getTotalRiskTypeCount() {
		JSONObject jso = new JSONObject();
		for (String s : EquipmentAssessmentManager.SECOND_RISK_TYPE) {
			switch (s) {
			case "反措未执行":
				jso.put(s, ea.getSecCounterMeasures().size());
				break;
			case "未处理缺陷":
				jso.put(s, ea.getSecDefects().size());
				break;
			case "超期服役":
				jso.put(s, ea.getSecLedgers().size());
				break;
			case "超期未检":
				jso.put(s, ea.getSecEquipmentChecks().size());
				break;
			case "通信中断":
				//jso.put(s, ea.countAllSeChannelAlarms());
				break;
			case "保护装置异常":
				jso.put(s, ea.countAllSeDevAlarms());
				break;
			case "保护响应异常":
				jso.put(s, ea.countAllSeActionExceptions());
				break;
			default:
				break;
			}
		}
		return jso;
	}

	/**
	 * 地理图上的饼形图
	 * 
	 * @param sid
	 * @return
	 */
	private String getMapPieChartOptionData(String sid) {
		// 获取变电站二次设备数量
		List<ProtectionEquipment> ps = cim.getProtectionEquipmentsByStationId(sid);
		int total = ps.size();
		// 获取影响风险等级的各个具体的记录列表
		EquipmentAssessment equip = ea.getSecondaryEquipmentAssessment(sid);
		JSONObject typeCountjso = new JSONObject();
		// 反措未执行
		List<SecondaryEquipmentCounterMeasuresSubInfo> fcs = equip
				.getSecondaryEquipmentCounterMeasuresInfoList();
		Map<String, List<SecondaryEquipmentCounterMeasuresSubInfo>> fcInfos = this
				.generateSecondaryEquipmentCounterMeasuresSubInfo(fcs);
		typeCountjso.put("反措未执行", fcInfos);

		// 未处理缺陷
		List<SecondaryEquipmentDefectInfo> defects = equip
				.getSecondaryEquipmentDefectInfoList();
		Map<String, List<SecondaryEquipmentDefectInfo>> defectInfos = this
				.generateSecondaryEquipmentDefectInfo(defects);
		typeCountjso.put("未处理缺陷", defectInfos);

		// 超期服役
		List<SecondaryEquipmentLedger> ledger = equip
				.getSecondaryEquipmentLedgerList();
		Map<String, List<SecondaryEquipmentLedger>> ledgerInfos = this
				.generateSecondaryEquipmentLedger(ledger);
		typeCountjso.put("超期服役", ledgerInfos);

		// 超期未检
		List<SecondaryEquipmentCheckInfo> checks = equip
				.getSecondaryEquipmentCheckInfoList();
		Map<String, List<SecondaryEquipmentCheckInfo>> checkInfos = this
				.generateSecondaryEquipmentCheckInfo(checks);
		typeCountjso.put("超期未检", checkInfos);

		// 通信中断
		/*List<ProtectDeviceAlarmModel> channelAlarms = equip
				.getProtectInterruptAlarmList();
		Map<String, List<ProtectDeviceAlarmModel>> channelAlarmInfos = this
				.generateProtectChannelAlarm(channelAlarms);
		typeCountjso.put("通信中断", channelAlarmInfos);*/

		// 保护装置异常
		List<ProtectDeviceAlarmModel> devAlarms = equip.getProtectDeviceAlarmList();
		Map<String, List<ProtectDeviceAlarmModel>> devAlarmInfos = this
				.generateProtectDeviceAlarm(devAlarms);
		typeCountjso.put("保护装置异常", devAlarmInfos);

		// 保护响应异常
		List<ProtectionActionInfoDTO> protectExceptionList = equip
				.getSecondaryEquipmentExceptionList();
		Map<String, List<ProtectionActionInfoDTO>> peInfos = this
				.generateProtectionActionInfoDTO(protectExceptionList);
		typeCountjso.put("保护响应异常", peInfos);

		// 主饼图数据[{name:xxx,value:1}]
		JSONArray pieMainValues = new JSONArray();
		for (String g : EquipmentAssessmentManager.SECOND_RISK_GROUP) {
			JSONObject tmp = new JSONObject();
			String[] types = getSecondaryRiskTypeByLevel(g);
			int count = 0;
			if ("正常".equals(g)) {
				count = total - fcInfos.size() - defectInfos.size()
						- ledgerInfos.size() - checkInfos.size()
						- devAlarmInfos.size()
						- peInfos.size();
			} else {
				for (String ts : types) {
					Object tclist = typeCountjso.get(ts);
					if (tclist != null && tclist instanceof Map) {
						int cttmp = ((Map) typeCountjso.get(ts)).size();
						count += cttmp;
					}
				}
			}
			tmp.put("name", g);
			tmp.put("value", count);
			tmp.put("itemStyle", getGroupColor(g));
			pieMainValues.add(tmp);
		}
		return pieMainValues.toString();
	}
}
